<template>
  <div class="material_model">
    <!-- class="noselect"  v-dialogdrag=" { target:'.el-dialog__header',container:'.el-dialog',border:'.el-dialog__wrapper'}"-->
    <el-dialog title="原料管理" class="noselect"
               :close-on-click-modal="false" :visible.sync="showDialog" :before-close="handleClose">
      <div style="margin: 20px;"></div>
      <el-form :model="modelForm" ref="modelForm" label-width="100px" class="demo-ruleForm material_form">
        <el-form-item label="" prop="downCategeryId" :rules="[]" class="el-form-item__content_margin" v-if="!edit">
          <div class="el-input el-input-group el-input-group--prepend ">
            <div class="el-input-group__prepend " >所属类别</div>
            <el-cascader class="el-cascader-margin w-100p" :options="treeData" size="medium"
                         :show-all-levels="false" v-model="downCategeryId" change-on-select
                         @change="getValue" @blur="closeCascader"/>

          </div>
        </el-form-item>

        <div v-if="storeType=='HB'">
          <el-form-item label=" " prop="materialType" :rules="[{ required: true, message: '请选择原料类型', trigger: 'change' }]">
            <div class="el-input el-input-group el-input-group--prepend el-input--medium">
              <div class="el-input-group__prepend" tabindex="-1">原料类型</div>
              <el-select :disabled="edit" v-model="modelForm.materialType" filterable  placeholder="请选择原料类型" class="w-100p"  size="medium"  >
                <el-option v-for="(item,index) in materialTypes"
                           :key="index"
                           :label="item.text"
                           :value="item.key"
                           :disabled="item.key && item.key=='PRODUCT'"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>
        </div>


        <el-form-item label=" " prop="no" :rules="[{ required: true, message: '原料编号不能为空且不能重复', trigger: 'blur' }]">
          <el-input placeholder="请输入原料编号" :disabled="edit" v-model="modelForm.no" size="medium" :maxlength="6">
            <template slot="prepend">
              <el-tooltip placement="top" content="请填写原料编号,不能填写已有编号">
                <el-button tabIndex="-1">原料编号</el-button>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label=" " prop="name" :rules="[{ required: true, message: '原料名称不能为空且不能重复', trigger: 'blur' }]">
          <el-input placeholder="请输入原料名称" :disabled="edit" v-model="modelForm.name" @blur="setPy()" size="medium" :maxlength="11">
            <template slot="prepend">
              <el-tooltip placement="top" content="请填写原料名称，不能填写已有名称">
                <el-button tabIndex="-1">原料名称</el-button>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label=" " prop="pinyin" :rules="[]" style="display: none">
          <el-input placeholder="请输入原料拼音" :disabled="edit" v-model="modelForm.pinyin" size="medium" :maxlength="20">
            <template slot="prepend">
              <el-tooltip placement="top" content="请填写原料拼音">
                <el-button tabIndex="-1">原料拼音</el-button>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label=" " prop="spell" :rules="[]" style="display: none">
          <el-input placeholder="请输入原料简码" v-model="modelForm.spell" size="medium" :maxlength="20">
            <template slot="prepend">
              <el-tooltip placement="top" content="请填写原料简码">
                <el-button tabIndex="-1">原料简码</el-button>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label=" " prop="goodsSpec" :rules="[]">
          <el-input placeholder="请输入规格型号" :disabled="edit" v-model="modelForm.goodsSpec" size="medium" :maxlength="20">
            <template slot="prepend">
              <el-tooltip placement="top" content="请填写规格型号">
                <el-button tabIndex="-1">规格型号</el-button>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label=" " prop="unit" :rules="[{ required: true, message: '请选择库存单位', trigger: 'change' }]">
          <div class="el-input el-input-group el-input-group--prepend el-input--medium">
            <div class="el-input-group__prepend" tabindex="-1">库存单位</div> <!--allow-create  remote  :remote-method="selectRemoteMethod"  default-first-option   autocomplete="on" -->
           <!-- <el-select :disabled="edit" v-model="modelForm.unit" filterable :filter-method="selectUnit" @blur="unitBlur"  placeholder="请选择" class="w-100p"  size="medium"  >
              <el-option v-for="(item,index) in units" :key="index" :label="item.name" :value="item.name"
                         :disabled="item.disabled" >
              </el-option>
            </el-select>-->
            <!--<el-autocomplete
              class="inline-input w-100p"
              v-model="modelForm.unit"
              :fetch-suggestions="querySearch"
              placeholder="请选择库存单位"
              custom-item="my-item-zh"
              @select="handleSelect"
            ></el-autocomplete>-->
            <el-autocomplete
              class="inline-input w-100p"
              v-model="modelForm.unit"
              :fetch-suggestions="querySearch"
              placeholder="请选择商品单位"
              custom-item="my-item-zh"
              @select="handleSelect"
              @change="findUnit"
            ></el-autocomplete>
          </div>
        </el-form-item>
        <el-form-item label=" " prop="minStock" :rules="[rules.numPot2]">
          <el-input :disabled="edit" placeholder="请输入最低库存" v-model.number="modelForm.minStock" @blur="isNum(modelForm,'minStock')" size="medium" :maxlength="10">
            <template slot="prepend">
              <el-tooltip placement="top" content="（不足最低库存时，库存报表以红色标识）">
                <el-button tabIndex="-1">最低库存</el-button>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label=" " prop="maxStock" :rules="[rules.numPot2]">
          <el-input :disabled="edit" placeholder="请输入最高库存" v-model.number="modelForm.maxStock" @blur="isNum(modelForm,'maxStock')" size="medium" :maxlength="10">
            <template slot="prepend">
              <el-tooltip placement="top" content="（高于最高库存时，库存报表以绿色标识）">
                <el-button tabIndex="-1">最高库存</el-button>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label=" " prop="storeMode" :rules="[]">
          <div class="el-input el-input-group el-input-group--prepend el-input--medium">
            <div class="el-input-group__prepend" tabindex="-1">储存方式</div>
            <el-select :disabled="edit" v-model="modelForm.storeMode" filterable placeholder="（根据所需选择储存方式，非必选！）"
                       class="w-100p"  size="medium">
              <el-option v-for="item in storeMode" :key="item.key" :label="item.text" :value="item.key">
              </el-option>
            </el-select>
          </div>
        </el-form-item>


        <!--商品条码 可以添加多个 start-->
        <!--<div v-if="storeType=='LS' || storeType=='SX'">-->
        <el-form-item label=" " prop=""   v-for="(item,index) in codeList" :key="index" style="padding-right: 55px">
          <el-input placeholder="请输入条码" v-model="item.code" :maxlength="13">
            <template slot="prepend">
              <el-button tabIndex="-1">条码{{index+1}}</el-button>
            </template>
            <template slot="append" v-if="index!=0"><i class="icon icon-jjian-" @click="delCode(index)"></i></template>
          </el-input>

          <div style="position: absolute;right:-41px; top: 2px; " @click="addCode()"><i class="icon icon-jia"
                                                                                        style="font-size: 23px;color:#20a0ff"></i></div>

        </el-form-item>
        <!--</div>-->
        <!--商品条码 可以添加多个 end-->


        <!--      <!--动态编辑[采购规格]--============================================-->
        <!--动态编辑[采购规格]-->
        <div class="cggg-con"
             v-for="(pur,index) in purchase">
          <div class="text-right" style="position: relative;">
            <el-button type="text" @click="delPurchase(index)" v-if="index!=0" tabIndex="-1">删除规格</el-button>
          </div>
          <el-form :model="pur" :ref="'pur'+index" style="height:230px;" class="demo-ruleForm">
            <el-form-item prop="purchaseSpec" :rules="[{ required: true, message: '采购规格不能为空且不能重复', trigger: 'blur' }]">
              <el-input :disabled="edit" placeholder="请输入采购规格" v-model="pur.purchaseSpec" size="medium">
                <template slot="prepend">
                  <el-tooltip placement="top" content="请填写采购规格, 例如 12瓶/箱">
                    <el-button tabIndex="-1">采购规格{{index+1}}</el-button>
                  </el-tooltip>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="purchaseUnit" :rules="[{ required: true, message: '请选择采购单位', trigger: 'change' }]"
                          class="el-form-item__content_margin"
                          style="margin-left: 0;">
              <div class="el-input el-input-group el-input-group--prepend el-input--medium">
                <div class="el-input-group__prepend" tabIndex="-1">采购单位</div><!--remote  allow-create default-first-option  :remote-method="selectPurUnit" -->
               <!-- <el-select :disabled="edit" v-model="pur.purchaseUnit" filterable :filter-method="selectPurchaseUnit" @blur="unitBlur"   placeholder="选择所需采购单位，必选！" class="w-100p" @focus="getIndex(index)" >
                  <el-option v-for="(item,itemIndex) in units" :key="itemIndex" :label="item.name" :value="item.name"
                             :disabled="item.disabled">
                  </el-option>
                </el-select>-->
                <el-autocomplete
                  :disabled="edit"
                  class="inline-input w-100p"
                  v-model="pur.purchaseUnit"
                  :fetch-suggestions="querySearch"
                  placeholder="请选择采购单位"
                  custom-item="my-item-zh"
                  @select="handleSelect2"
                  @click.native="selectConsumeUnit1(index)"
                ></el-autocomplete>
              </div>
            </el-form-item>
            <el-form-item prop="purchaseCount" :rules="[rules.numPot2]">
              <el-input placeholder="请输入采购单位与库存单位的换算值" size="medium" v-model="pur.purchaseCount" :disabled="edit" @blur="isPositive(pur,'purchaseCount')">
                <template slot="prepend">
                  <el-tooltip placement="top" content="此字段表示一个采购单位对应多少个库存单位，比如:1箱(采购单位)=10瓶(库存单位),此处应填写10">
                    <el-button tabIndex="-1">采购->库存单位换算值</el-button>
                  </el-tooltip>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="purchasePrice" :rules="[rules.numPot2]">
              <el-input :disabled="edit" placeholder="请输入此采购规格的采购单价" v-model.number="pur.purchasePrice" size="medium" :maxlength="10"
                        @blur="isPositive(pur,'purchasePrice')">
                <template slot="prepend">
                  <el-tooltip placement="top" content="（填写此采购规格的采购单价，例如：1，1.5...）">
                    <el-button tabIndex="-1">此规格价格</el-button>
                  </el-tooltip>
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </div>

        <div class="text-right" style="margin:10px;margin-right: 100px;">
          <el-button type="text" :disabled="edit" @click="addPurchase(index)">添加采购规格</el-button>
        </div>

      <!--  <el-form-item label=" " prop="purchaseNewPrice">
          <el-input placeholder="请输入最新采购单价" v-model.number="modelForm.purchaseNewPrice" size="medium" :maxlength="10">
            <template slot="prepend">
              <el-tooltip placement="top" content="请填写最新采购单价">
                <el-button tabIndex="-1">最新采购单价</el-button>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>-->
        <el-form-item label=" " prop="consumeUnit" :rules="[{ required: true, message: '请选择消耗单位', trigger: 'blur' }]">
          <div class="el-input el-input-group el-input-group--prepend el-input--medium">
            <div class="el-input-group__prepend" tabindex="-1">消耗单位</div> <!--default-first-option allow-create remote :remote-method="selectRemoteMethod1"-->
           <!-- <el-select :disabled="edit" v-model="modelForm.consumeUnit"  filterable  :filter-method="selectConsumeUnit" @blur="unitBlur"
                       class="w-100p"
                       placeholder="（选择所需消耗单位，必选！）">
              <el-option v-for="(item,itemIndex) in units" :key="itemIndex" :label="item.name" :value="item.name"
                         :disabled="item.disabled">
              </el-option>
            </el-select>-->

            <el-autocomplete
              class="inline-input w-100p"
              v-model="modelForm.consumeUnit"
              :fetch-suggestions="querySearch"
              :disabled="edit"
              placeholder="请选择消耗单位"
              custom-item="my-item-zh"
              @select="handleSelect1"
            ></el-autocomplete>
          </div>
        </el-form-item>
        <el-form-item label=" " prop="consumeRates" :rules="[]">
          <el-input placeholder="请输入库存单位与消耗单位间的换算值" v-model.number="modelForm.consumeRates" :disabled="edit" size="medium"
                    @blur="isPositive(modelForm,'consumeRates')">
            <template slot="prepend">
              <el-tooltip placement="top" content="此字段表示一个库存单位对应多少个消耗单位,比如:1瓶(库存单位)=500克(消耗单位)，此处应填写500">
                <el-button tabIndex="-1">库存->消耗单位换算值</el-button>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label=" " prop="orderPriceBom" :rules="[]">
          <el-input :disabled="edit" placeholder="请输入库存单位成本价" v-model.number="modelForm.orderPriceBom" size="medium" :maxlength="10">
            <template slot="prepend">
              <el-tooltip placement="top" content="请填写库存单位成本价(库存预估成本单价),例如：1,1.5...">
                <el-button tabIndex="-1">库存单位成本价</el-button>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label=" " prop="orderType" :rules="[{ required: true, message: '选择所需订货类型', trigger: 'blur',  }]">
          <div class="el-input el-input-group el-input-group--prepend el-input--medium">
            <div class="el-input-group__prepend" tabindex="-1">订货类型</div>
            <el-select :disabled="edit" v-model.number="modelForm.orderType" filterable size="medium"
                       class="w-100p"
                       placeholder="请选择订货类型">
              <el-option v-for="item in orderTypes" :key="item.key" :label="item.text" :value="item.key">
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label=" " prop="stocktakeType" :rules="[{ required: true, message: '请选择盘点类型', trigger: 'blur' }]">
          <div class="el-input el-input-group el-input-group--prepend el-input--medium">
            <div class="el-input-group__prepend" tabindex="-1">盘点类型</div>

            <el-select :disabled="edit" v-model="modelForm.stocktakeType" filterable placeholder="请选择盘点类型" class="w-100p" size="medium">
              <el-option v-for="item in stocktakeTypes" :key="item.key" :label="item.text"
                         :value="item.key">
              </el-option>
            </el-select>
          </div>
        </el-form-item>


        <el-form-item  prop="shared" :rules="[]">
          <div class="el-input el-input-group el-input-group--prepend">
            <div class="el-input-group__prepend">是否共享</div>
            <div style="border:1px solid #ccc;line-height: 30px;padding:0px 35px;min-height: 30px;" class="text-left">
                <el-checkbox :disabled="edit" v-model="modelForm.shared">共享</el-checkbox>
            </div>
          </div>
        </el-form-item>

        <el-form-item label=" " prop="state" :rules="[]">
          <div class="el-input el-input-group el-input-group--prepend addprepend el-input--medium">
            <div class="el-input-group__prepend addPrependText-medium" tabIndex="-1">
              <span>状态</span>
            </div>
            <el-radio-group :disabled="edit" class="radio-group w-100p text-left" v-model="modelForm.state" size="medium" >
              <el-radio v-for="item in states" :label="item.key" :value="item.key" :key="item.key">
                {{item.text}}
              </el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
      </el-form>
      <div class="foot-bar-button">
        <el-button v-if="!edit" type="primary" @click="submitForm('modelForm')" size="medium">提交</el-button>
        <el-button @click="resetForm('modelForm')" size="medium">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import Vue from 'vue';
  Vue.component('my-item-zh', {
    functional: true,
    render: function (h, ctx) {
      var item = ctx.props.item;
      return h('li', ctx.data, [
        h('div', { attrs: { class: 'name' } }, [item.name]),
      ]);
    },
    props: {
      item: { type: Object, required: true }
    }
  });
  //注意路径
  export default {
    props: ['isShow', 'id','edit'],  //参数
    data() {
      return {
        modelForm: {
          shared:false
        },
        downCategeryId: [],
        treeData:[],
        showDialog: false,
        activityId: "",
        isSave: true,
        purchase: [{purchaseSpec: "", purchaseUnit: "", purchaseCount: 1, purchasePrice: 0, isDeleted: false,hasDef:false}],
        purchaseModel: {purchaseSpec: "", purchaseUnit: "", purchaseCount: 0, purchasePrice: 0, isDeleted: true, hasDef:false},
        units: [],
        copyUnits: [],
        storeMode: [],
        states: [],
        orderTypes: [],
        stocktakeTypes: [],
        purIndex:"",
        materialTypes:[],
        storeId:window.localStorage.getItem("dishKuId"),
        storeType: window.localStorage.getItem("dishKuType"),
        selectUnitIndex:0,
        codeList:[{code:""}],//商品条码
      };
    },
    watch: {
      isShow: function (newValue, oldValue) {
        this.modelForm = {};
        this.purchase = [];
        this.downCategeryId = [];
        this.showDialog = newValue;
        if (newValue) {
          if (this.id != '') {
            this.activityId = this.id;
            this.isSave = false;
            this.$axios.get("materials/materials/" + this.activityId + "/update",{sid:this.storeId}).then(data => {
              var dataValue = data.content;
              //原品单位启用、禁用处理
              dataValue.units.map(function (item) {
                if (item.state && item.state.key == 'DISABLED') {
                  item.disabled = true;
                } else {
                  item.disabled = false;
                }
              });
//              this.materialTypes = [];
//              console.log("-----------storeType----:",this.storeType);
//              console.log("-----------dataValue.materialTypes----:",dataValue.materialTypes);
//              if(this.storeType!='HB'){
//                if(dataValue.materialTypes && dataValue.materialTypes.length>0){
//                  for(var i=0;i<dataValue.materialTypes.length;i++){
//                    if(dataValue.materialTypes[i].key!='MATERIAL'){
//                      this.materialTypes.push(dataValue.materialTypes[i]);
//                    }
//                  }
//                }
//              }else{
                this.materialTypes = dataValue.materialTypes;
//              }
              if(dataValue.material.storeId){
                dataValue.material.shared = false;
              }else {
                dataValue.material.shared = true;
              }

//              console.log(this.modelForm.shared);

              this.modelForm = dataValue.material;
              this.units = dataValue.units;
              this.copyUnits = dataValue.units;
              this.storeMode = dataValue.storeMode;
              this.states = dataValue.states;
              this.orderTypes = dataValue.orderTypes;
              this.stocktakeTypes = dataValue.stocktakeTypes;
              var tree = dataValue.treeData;
              this.newLabel(tree);
              this.treeData = tree;


              var ids = dataValue.material.category.parentIds.replace("0/", "");
              this.downCategeryId = [];
              if (dataValue.material.category.parentId) {
                this.downCategeryId.push(dataValue.material.category.parentId + '');
              }
              this.downCategeryId.push(dataValue.material.category.id + '');
//              console.log( this.downCategeryId);
              dataValue.material.category = dataValue.material.category.parentId;
              this.purchase.splice(0, 1);
              for (var i = 0; i < dataValue.purchase.length; i++) {
                dataValue.purchase[i].isDeleted = false;
                this.purchase.push(dataValue.purchase[i]);
              }



            });
          } else {
            this.isSave = true;
            this.purchase = [{
              purchaseSpec: "",
              purchaseUnit: "",
              purchaseCount: 1,
              purchasePrice: 0,
              isDeleted: false
            }];
            this.$axios.get("materials/materials/create",{sid:this.storeId}).then(data => {
              var dataValue = data.content;
              this.modelForm = dataValue.material;
              //原料单位启用、禁用处理
              dataValue.units.map(function (item) {
                if (item.state && item.state.key == 'DISABLED') {
                  item.disabled = true;
                } else {
                  item.disabled = false;
                }
              })
              this.materialTypes = dataValue.materialTypes;
              this.modelForm = dataValue.material;
              this.units = dataValue.units;
              this.copyUnits = dataValue.units;
              this.storeMode = dataValue.storeMode;
              this.states = dataValue.states;
              this.orderTypes = dataValue.orderTypes;
              this.stocktakeTypes = dataValue.stocktakeTypes;

              var tree = dataValue.treeData;
              this.newLabel(tree);
              this.treeData = tree;

            });
          }
        }
      }
    },
    created() {
      window.this = this;
    },
    methods: {
      addCode(){
        this.codeList.push({code:""});
      },
      delCode(index){
        if(this.codeList.length>1){
          this.codeList.splice(index,1);
        }else{
          this.$message.info("最少保留一条");
        }
      },
      findUnit(){
        var unit=this.units.find(data=>{
          if(data.name==this.modelForm.unit){
            return true;
          }else{
            return false;
          }
        })

      },

      querySearch(queryString, cb) {

        var restaurants = this.units;

        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        if(results.length<=0){
          this.$message.error("该单位不存在")
        }
        for(let i of results){
          i.value = i.name;  //将想要展示的数据作为value
        }
        cb(results);
      },
      createFilter(queryString) {
        return (restaurant) => {

          return (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0) && restaurant.state=='NORMAL';
        };
      },
      handleSelect(item){
        this.modelForm.unit=item.name
      },

      handleSelect1(item){
        this.modelForm.consumeUnit=item.name
      },
      handleSelect2(item){
        this.purchase[this.selectUnitIndex].purchaseUnit=item.name
      },
      selectConsumeUnit1(index){
        console.log("vvvvvvvvvvvvvvvvvv");
        console.log(index);
        this.selectUnitIndex=index;
      },
      handleSelect2(item){
        console.log(item);
        console.log("vbbbbbbbbbbbbbbbbbb");
        this.purchase[this.selectUnitIndex].purchaseUnit=item.name;
        this.$forceUpdate();
      },


      getIndex(index){
        this.purIndex=index;
      },
      selectPurUnit(query){

        if(!query){
          return;
        }
        if(query!=''){
          var flag=0;
          for(var i=0;i<this.units.length;i++){
            if(query!=this.units[i].name){
              flag++;
            }
          }
          if(flag===0){
            this.units.push({id:"",name:query});
          }
          this.$forceUpdate();
          this.purchase[this.purIndex].purchaseUnit=query;
        }
      },
      selectRemoteMethod(query){

        if(!query){
          return;
        }
         if(query!=''){
           var flag=0;
           for(var i=0;i<this.units.length;i++){
             if(query!=this.units[i].name){
               flag++;
             }
           }
           //不存在
           if(flag===0){
             this.units.push({id:"",name:query});
           }

           this.$forceUpdate();
           this.modelForm.unit=query;
         }

      },
      unitBlur(){
        this.units = this.copyUnits;
      },
      selectPurchaseUnit(val){
        if (val) { //val存在
          this.units =  this.copyUnits.filter((item) => {
            if(val==item.name){
              return true;
            }
          })
          if(!this.units || (this.units && this.units.length==0)){
            this.units.push({
              name:val
            });
          }
        } else { //val为空时，还原数组
          this.units.push({
            name:val
          });
        }
        this.$forceUpdate();
        this.purchase[this.purIndex].purchaseUnit=val;
      },
      selectUnit(val){
        if (val) { //val存在
          this.units =  this.copyUnits.filter((item) => {
            if(val==item.name){
              return true;
            }
          })
          if(!this.units || (this.units && this.units.length==0)){
            this.units.push({
              name:val
            });
          }
        } else { //val为空时，还原数组
          this.units.push({
            name:val
          });
        }
        this.$forceUpdate();
        this.modelForm.unit=val;
      },
      selectConsumeUnit(val){
        if (val) { //val存在
         this.units =  this.copyUnits.filter((item) => {
            if(val==item.name){
              return true;
            }
          })
          if(!this.units || (this.units && this.units.length==0)){
            this.units.push({
              name:val
            });
          }
        } else { //val为空时，还原数组
          this.units.push({
            name:val
          });
        }
        this.$forceUpdate();
        this.modelForm.consumeUnit=val;
      },
      selectRemoteMethod1(query){
        if(query!=''){
          var flag=0;
          for(var i=0;i<this.units.length;i++){
            if(query!=this.units[i].name){
              flag++;
            }
          }
          if(flag===0){
            this.units.push({id:"",name:query});
            this.modelForm.consumeUnit=query;
          }
          this.$forceUpdate();
          this.modelForm.consumeUnit=query;
        }
      },
      closeCascader(){

      },
      getValue(value) {
        if (value != null) {
          this.modelForm.category = value[value.length - 1];
        }
      },
      /*删除*/
      delPurchase(index) {
        if (this.purchase.length > 1) {
          this.purchase.splice(index, 1);
        } else {
          this.$message.info("最少保留一条");
        }
      },
      addPurchase(index) {
        this.purchase.push(this.purchaseModel);
        this.purchaseModel = {
          purchaseSpec: "",
          purchaseUnit: null,
          purchaseCount: 0,
          purchasePrice: 0,
          isDeleted: true,
          hasDef:false
        };
      },
      isPositive(item, key) {
        let num = parseFloat(item[key]);
        if (!isNaN(num) && (isFinite(num)) && (num > 0)) {
          item[key] = num + "";
        } else {
          item[key] = "1";
        }
      },
      setPy() {
        if(!this.modelForm.name){
          return;
        }
        this.modelForm.pinyin = window.getPy(this.modelForm.name);
        this.modelForm.spell = window.getIndexPy(this.modelForm.name);
      },
      newLabel(newList) {
        if (newList) {
          for (var i = 0; i < newList.length; i++) {
            newList[i].label = newList[i].name;
            newList[i].value = newList[i].id + "";
            if (newList[i].children.length == 0) {
              newList[i].children = null;
            } else {
              for (var s = 0; s < newList[i].children.length; s++) {
                newList[i].children[s].label = newList[i].children[s].name;
                newList[i].children[s].value = newList[i].children[s].id + "";
                newList[i].children[s].children = null;
              }
            }
          }
        }
      },
      goBack() {
        this.router.go(-1);
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var data = {};

            if(this.modelForm.shared){
//              共享
              this.modelForm.storeId='';
            }else {
              this.modelForm.storeId = this.storeId;
            }




            data.material = this.modelForm;
            data.purchase = this.purchase;
            this.modelForm.category = this.downCategeryId[this.downCategeryId.length - 1];
            this.modelForm.category = this.downCategeryId[this.downCategeryId.length - 1];
            if (!this.modelForm.category) {
              this.modelForm.category = 0;
            }
            if (this.modelForm.category == 0) {
              this.$message.error("请选择类别");
              return false;
            }


            var codes = "";

            if(this.codeList && this.codeList.length>0){
              for(var i=0;i<this.codeList.length;i++){
                if(this.codeList[i].code!=''){
//                  codes.push(this.codeList[i].code);
                  codes += ","+this.codeList[i].code;
                }
              }
            }

            if(codes){
              data.material.codes =codes +",";
            }else {
              data.material.codes ="";
            }



            // data = JSON.stringify(data);
            if(this.purchase && this.purchase.length>0){
              for (let i = 0; i < this.purchase.length; i++) {
//                console.log(this.$refs[ref])
                let ref = 'pur' + i;

                this.$refs[ref][0].validate((valid) => {
                  if (valid) {
                    if (i == this.purchase.length - 1) {
                      if (this.isSave) {
                        this.$axios.post("materials/materials/create", data,'json').then(data => {
                          if (data.status == 200) {
                            this.$message({
                              message: data.message,
                              type: 'success'
                            });
                            this.$emit('addSuccess');
                          } else {
                            this.$message.error(data.message);
                          }

                        })

                      } else {
//                        console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>bbbbbbbb");
                        this.$axios.put("materials/materials/" + this.activityId + "/update",data,'json').then(data => {
                          if (data.status == 200) {
                            this.$message({
                              message: data.message,
                              type: 'success'
                            });
                            this.$emit('addSuccess');
                          } else {
                            this.$message.error(data.message);
                          }
                        })
                      }
                    }
                  } else {
                    this.$message.error("请检查采购规格");
                    return false;
                  }
                })
              }
            }else {
              this.$message.error("采购规格至少保留一条");
              return false;
            }

          } else {
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$emit('close');
        this.showDialog = false;
        this.edit=false;
      },
      handleClose(done) {
        this.$emit('close');
        this.showDialog = false;
        this.edit=false;
        done();
      },
      isNum(item, key) {
        var r = /^\+?[1-9][0-9]*$/;
        if (!r.test(item[key])) {
          item[key] = "0.00"
        } else {
          item[key] = item[key]
        }
      },
      isDouble(item, key) {
        var isNum = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
        if (!isNum.test(item[key])) {
          item[key] = "0.00"
        } else {
          item[key] = item[key]
        }
      }
    }
  }
</script>
<style scoped>
  /*动态编辑[采购规格]*/
  .cggg-con {
    width: 570px;
    background-color: #F9F9F9;
    border: 1px solid #cccccc;
    border-top: 3px solid #1ab394;
    margin: 0 10px 10px 100px;
    padding: 10px 15px 15px 15px;

  }

</style>
